import React, { useRef, useState, useCallback } from "react";
import { Button, Form, Input, Modal, Space, Tabs, message } from "antd";
import XlCheckBox from "@/components/Form/XlCheckBox";
import QuotationTableAll from "./modules/All";
import QuotationTableTodo from "./modules/Todo";
import QuotationTableDoing from "./modules/Doding";
import QuotationTableDone from "./modules/Done";
import XlSelect from "@/components/Form/XlSelect";
import { useComponentDidMount } from "@/hooks";
import { useModel } from "@umijs/max";
import LineQuoteImport from "../modals/LineQuoteImport";
import { useRequest } from "ahooks";
import { lpsLineQuoteImportQuote, lineQuoteRapidQuote, lpsLineQuoteOffSale, lpsLineQuoteOnSale, fetchLineQuotetabNum } from '../services';
import { fetchDictTemplatePath, fetchDomesticWhOptions, fetchSettlementDateLatestWeek } from "@/pages/BasicInfo/services";
import { warehouseTypes } from "@/constants/types";
import LineQuoteCopy from "../modals/LineQuoteCopy";
import { downloadFile } from "@/utils/util";
import { ArrowDownOutlined } from "@ant-design/icons";

const {Item} = Form;

const LineQuote = () => {
  const [form] = Form.useForm();
  const allRef = useRef();
  const todoRef = useRef();
  const doingRef = useRef();
  const doneRef = useRef();
  const {getDict} = useModel('dictModel');
  const countrys = getDict('country');
  const prdList = getDict('prdType');
  const destTypes = getDict('destType');
  const deliveryMethods = getDict('deliveryMethod');
  const { settlementWeek } = useModel('settlementWeekModel');
  const {currentWeek} = settlementWeek || {};
  const initValues = {weeks: currentWeek ? [currentWeek] : []};

  const [activeKey, setActiveKey] = useState<string>('all');
  const [tabNum, setTabNum] = useState<any>({});
  const [searchValue, setSearchValue] = useState<Object>({...initValues});
  const {data: warehouseList} = useRequest(fetchDomesticWhOptions);
  const {data: weeks} = useRequest(fetchSettlementDateLatestWeek);

  const [visible, setVisible] = useState<boolean>(false);
  const {loading, runAsync: lpsLineQuoteImportQuoteApi} = useRequest(lpsLineQuoteImportQuote, {manual: true});

  const [quickQuoteVisible, setQuickQuoteVisible] = useState<boolean>(false);
  const {loading: quickQuoteLoading, runAsync: lineQuoteRapidQuoteApi} = useRequest(lineQuoteRapidQuote, {manual: true});

  const [temPath, setTemPath] = useState(null);

  const getParams  = () => {
    const params = form.getFieldsValue();
    return {
      ...params,
      weeks: params?.weeks?.includes('all') ? undefined : params?.weeks,
      countries: params?.countries?.includes('all') ? undefined : params?.countries,
      products: params?.products?.includes('all') ? undefined : params?.products,
      deliveryMethods: params?.deliveryMethods?.includes('all') ? undefined : params?.deliveryMethods,
      cwhCodes: params?.cwhCodes?.includes('all') ? undefined : params?.cwhCodes,
    }
  }
  
  const fetchTabNum = async () => {
    const res = await fetchLineQuotetabNum(getParams());
    setTabNum({
      all: res?.totalNum || 0,
      todo: res?.waitSaleNum || 0,
      doing: res?.onSaleNum || 0,
      done: res?.offSaleNum || 0,
    });
  }


  const tabChange = (key: string) => {
    setActiveKey(key);
  }

  const getTabTitle = useCallback((key: string) => {

    interface TitleMaps {
      [key: string]: string;
    }
    const titleMaps: TitleMaps = {
      all: '全部',
      todo: '待上架',
      doing: '售卖中',
      done: '已停售'
    }
    const title = titleMaps?.[key];
    const num = tabNum?.[key] > 0 ? ` ( ${tabNum?.[key]} ) ` : '';
    return title + num;
  }, [JSON.stringify(tabNum)]);

  const refreshNum = () => {
    fetchTabNum();
  }

  const items = [
    {
      key: 'all',
      label: getTabTitle('all'),
      children: <QuotationTableAll refreshNum={refreshNum} activeKey={activeKey} searchValue={searchValue} tabKey="all" ref={allRef} />,
    },
    {
      key: 'todo',
      label: getTabTitle('todo'),
      children: <QuotationTableTodo refreshNum={refreshNum} activeKey={activeKey} searchValue={searchValue} tabKey="todo" ref={todoRef} />,
    },
    {
      key: 'doing',
      label: getTabTitle('doing'),
      children: <QuotationTableDoing refreshNum={refreshNum} activeKey={activeKey} searchValue={searchValue} tabKey="doing" ref={doingRef} />,
    },
    {
      key: 'done',
      label: getTabTitle('done'),
      children: <QuotationTableDone refreshNum={refreshNum} activeKey={activeKey} searchValue={searchValue} tabKey="done" ref={doneRef} />,
    },
  ];
  
  interface RefMaps {
    [key: string]: React.RefObject<any>;
  }

  const refMaps: RefMaps = {
    all: allRef,
    todo: todoRef,
    doing: doingRef,
    done: doneRef,
  }

  const search = () => {
    setTimeout(() => {
      refMaps[activeKey]?.current?.refreshTable();
    }, 0)
  }
  const handleSearch = () => {
    setSearchValue(getParams());
    refreshNum();
    search();
  }
  const handleReset = () => {
    form.resetFields();
    setSearchValue({});
    refreshNum();
    search();
  }


  const lineQuoteImportProps = {
    visible,
    loading,
    onCancel: () => {
      setVisible(false);
    },
    onSubmit: async (params: any) => {
      const res = await lpsLineQuoteImportQuoteApi(params);
      if (res?.code === '0') {
        lineQuoteImportProps.onCancel();
        message.success('导入成功!');
      }
    }
  }
  const quickQuoteProps = {
    visible: quickQuoteVisible,
    title: "快速报价",
    loading: quickQuoteLoading,
    onCancel: () => {
      setQuickQuoteVisible(false);
    },
    onSubmit: async (params: any) => {
      const res = await lineQuoteRapidQuoteApi(params);
      if (res?.code === '0') {
        quickQuoteProps.onCancel();
        message.success('操作成功!');
        search();
      }
    }

  }

  const handleImport = () => {
    setVisible(true);
  }
  const handleBatchPut = () => {
    Modal.confirm({
      title: '上架提醒',
      content: '是否确定将选中的批量上架？',
      onOk: () => {
        const list = refMaps[activeKey]?.current?.getSelections();
        lpsLineQuoteOnSale({ids: list}).then(
          res => {
            if (res?.code === '0') {
              message.success('上架成功');
              refreshNum();
              refMaps[activeKey]?.current?.refreshTable();
            } else {
              message.warning(res?.msg || '上架失败!');
            }
          }
        )
      }
    });
  }
  const handleQuickQuote = () => {
    setQuickQuoteVisible(true);
  }
  const handleBatchOff = () => {
    Modal.confirm({
      title: '停售提醒',
      content: '是否确定将选中的批量停售？',
      onOk: () => {
        const list = refMaps[activeKey]?.current?.getSelections();
        lpsLineQuoteOffSale({ids: list}).then(
          res => {
            if (res?.code === '0') {
              message.success('停售成功');
              refreshNum();
              refMaps[activeKey]?.current?.refreshTable();
            } else {
              message.warning(res?.msg || '停售失败!');
            }
          }
        )
      }
    });
  }

  const getTabBarExtraRightContent = () => {
    if(activeKey === 'all') {
      return {
        right: (
          <Space>
            <Button type="primary" key="quickQuote" onClick={handleQuickQuote}>快速报价</Button>
            {temPath && <Button type="primary" onClick={() => downloadFile(temPath)}><ArrowDownOutlined />导入报价模板</Button>}
            <Button type="primary" key="handleImport" onClick={handleImport}>导入报价</Button>
          </Space>
        )
      };
    }
    if(activeKey === 'todo') {
      return {
        right: <Button type="primary" key="handleBatchPut" onClick={handleBatchPut}>批量上架</Button>
      };
    }
    if(activeKey === 'doing') {
      return {
        right: <Button type="primary" key="handleBatchOff" onClick={handleBatchOff}>批量停售</Button>
      };
    }
    if(activeKey === 'done') {
      return {
        right: <Button type="primary" key="handleBatchPut" onClick={handleBatchPut}>重新批量上架</Button>
      };
    }
    return undefined;
  }


  useComponentDidMount(() => {
    fetchTabNum();
    fetchDictTemplatePath({templateKey: "quoteTemplate"}).then(
      res => {
        setTemPath(res);
      }
    )
  });
  
  return (
    <>
      <Form form={form} initialValues={initValues} layout="inline" >
        <Item name="weeks" label="周次" style={{marginBottom: 15}}>
          <XlCheckBox.ButtonGroup options={weeks?.map((v: {label: String, value: String}) => ({label: v, value: v}))} />
        </Item>
        <Item name="countries" label="国家" style={{marginBottom: 15}}>
          <XlCheckBox.ButtonGroup options={countrys} />
        </Item>
        <Item name="products" label="产品" style={{marginBottom: 15}}>
          <XlCheckBox.ButtonGroup options={prdList} />
        </Item>
        <Item label="目的地" style={{marginBottom: 15}}>
          <Space.Compact>
            <Item name="destType" noStyle>
              <XlSelect options={destTypes} style={{width: 100}} />
            </Item>
            <Item name="destCode" noStyle>
              <Input style={{width: 150}} />
            </Item>
          </Space.Compact>
        </Item>
        <Item name="deliveryMethods" label="派送方式" style={{marginBottom: 15}}>
          <XlCheckBox.ButtonGroup options={deliveryMethods} />
        </Item>
        <Item name="cwhCodes" label="收货仓库" style={{marginBottom: 15}}>
          <XlCheckBox.ButtonGroup options={(warehouseList || [])?.map((v: warehouseTypes) => ({label: v?.name, value: v?.code}))} />
        </Item>
        <Item>
          <Space>
            <Button type="primary" onClick={handleSearch}>查询</Button>
            <Button type="default" onClick={handleReset}>重置</Button>
          </Space>
        </Item>
      </Form>
      <Tabs
        activeKey={activeKey}
        onChange={tabChange} 
        tabBarExtraContent={getTabBarExtraRightContent()}
        items={items}
      />
      {visible && <LineQuoteImport {...lineQuoteImportProps} />}
      {quickQuoteVisible && <LineQuoteCopy {...quickQuoteProps} />}
    </>
  );
};


export default LineQuote;